<template>
  <van-picker :class="{ open, }" show-toolbar :title="title" :columns="columns" @change="handleChangeArea" @cancel="handelCancel" @confirm="handleSelectArea" />
</template>
<script>
import addrData from "./addr-data";
const noop = () => {};
export default {
  props: {
    title: {
      type: String,
      required: false
    },
    open: {
      type: Boolean,
      required: false,
      default: true
    },
    change: {
      type: Function,
      required: false,
      default: noop
    },
    cancel: {
      type: Function,
      required: false,
      default: noop
    },
    confirm: {
      type: Function,
      required: false,
      default: noop
    }
  },
  data() {
    // console.log(addrData['110000'].children['110100'].children);

    return {
      columns: [
        {
          values: Object.values(addrData).map(d => ({
            text: d.name,
            value: d.code
          }))
        },
        {
          values: Object.values(addrData["110000"].children).map(d => ({
            text: d.name,
            value: d.code
          }))
        },
        {
          values: Object.values(
            addrData["110000"].children["110100"].children
          ).map(d => ({ text: d.name, value: d.code }))
        }
      ]
    };
  },
  methods: {
    handleSelectArea(data) {
      this.$emit("confirm", data);
    },
    handelCancel() {
      this.$emit("cancel");
    },
    handleChangeArea(picker, value, index) {
      let [province, city, area] = value;
      let cityList;
      if (index <= 0) {
        cityList = Object.values(addrData[province.value].children).map(d => ({
          text: d.name,
          value: d.code
        }));
        picker.setColumnValues(1, cityList);
      }
      if (index <= 1) {
        city = (cityList && cityList[0]) || city;
        const children = addrData[province.value].children[city.value].children;

        if (children) {
          picker.setColumnValues(
            2,
            Object.values(children).map(d => ({ text: d.name, value: d.code }))
          );
        } else {
          picker.setColumnValues(2, []);
        }
      }
      this.$emit("change", value);
    }
  }
};
</script>
<style lang="less">
.van-picker {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 100;
  transform: translateY(100%);
  transition: 300ms transform;

  &.open {
    transform: translateY(0);
  }
}
</style>
